package com.shenchuangit.tm.sdk.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Random;

/**
 * Rest Template 工具类
 *
 * @author FlyFive
 */
public class CommonUtils {

    public static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);

    private static RestTemplate restTemplate;

    private static ObjectMapper objectMapper;

    /**
     * 根据当前时间计算时间戳，以秒为单位
     *
     * @return 时间戳字符串
     */
    public static String calTimestamp() {
        return calTimestamp(new Date());
    }

    /**
     * 根据传递参数计算时间戳，以秒为单位
     *
     * @return 时间戳字符串
     */
    public static String calTimestamp(Date date) {
        String curTimestamp = String.valueOf(date.getTime());
        curTimestamp = curTimestamp.substring(0, curTimestamp.length() - 3);
        logger.info("时间戳:{}", curTimestamp);
        return curTimestamp;
    }

    /**
     * 单例构造 RestTemplate
     *
     * @return RestTemplate实例
     */
    public static RestTemplate getSingletonRestTemplate() {
        if (null == restTemplate) {
            restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        }

        return restTemplate;
    }

    /**
     * 单例构造 jackson
     *
     * @return jackson 实例
     */
    public static ObjectMapper getSingletonJackson() {
        if (null == objectMapper) {
            objectMapper = new ObjectMapper();
        }

        return objectMapper;
    }

    /**
     * 对象 转 json
     *
     * @param object 将要转换的对象
     * @return json字符串
     */
    public static String toJson(Object object) {
        String jsonStr = "";
        try {
            jsonStr = CommonUtils.getSingletonJackson().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.info("对象生成JSON错误");
        }

        return jsonStr;
    }

    /**
     * json 转 对象
     *
     * @param json  json字符串
     * @param clazz 将要转换为的Class
     * @param <T>   泛型
     * @return 对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        T instance = null;
        try {
            instance = CommonUtils.getSingletonJackson().readValue(json, clazz);
        } catch (IOException e) {
            logger.info("JSON串解析错误：{}", json);
        }

        return instance;
    }

    /**
     * 生成随机数字符串
     *
     * @return int型随机数字符串
     */
    public static String genRandomIntStr() {
        Random random = new Random();
        String randomIntStr = String.valueOf(random.nextInt(100000000));

        logger.info("随机数:{}", randomIntStr);
        return randomIntStr;
    }
}
